import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:video_player/video_player.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';

part 'video_play_production.page.dart';

/// 视频播放页面
///
/// 全屏播放视频
@PagePath('/video/:dynamicId/:mediaIndex')
class VideoPlayProduction extends StatefulWidget {
  const VideoPlayProduction({
    required this.dynamicId,
    required this.mediaIndex,
    super.key,
  });

  final String dynamicId;
  final String mediaIndex;

  @pageRouteQuery
  static RouteQuery query({
    required String dynamicId,
    required int mediaIndex,
  }) => _$VideoPlayProductionQuery().call(
    dynamicId: dynamicId,
    mediaIndex: mediaIndex.toString(),
  );

  @override
  State<VideoPlayProduction> createState() => _VideoPlayProductionState();
}

class _VideoPlayProductionState extends State<VideoPlayProduction> {
  VideoPlayerController? _controller;
  bool _isInitialized = false;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _initializeVideo();
  }

  void _initializeVideo() {
    // 延迟初始化，等待 didChangeDependencies
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_controller == null && _errorMessage == null) {
      _initVideoWithContext();
    }
  }

  void _initVideoWithContext() async {
    try {
      final dynamicRoom = GlobalStateProvider.dynamicRoomOf(context);
      final dynamic = dynamicRoom.fetchDynamicById(widget.dynamicId);

      if (dynamic == null || dynamic.mediaType != 'video') {
        if (mounted) {
          setState(() {
            _errorMessage = '视频不存在';
          });
        }
        return;
      }

      final mediaIndexInt = int.parse(widget.mediaIndex);
      if (mediaIndexInt >= dynamic.mediaUrls.length) {
        if (mounted) {
          setState(() {
            _errorMessage = '视频索引超出范围';
          });
        }
        return;
      }

      final videoUrl = dynamic.mediaUrls[mediaIndexInt];

      // 判断是 assets 文件还是本地文件
      if (videoUrl.startsWith('assets/')) {
        _controller = VideoPlayerController.asset(videoUrl);
      } else {
        // 检查本地文件是否存在
        final videoFile = File(videoUrl);
        if (!await videoFile.exists()) {
          if (mounted) {
            setState(() {
              _errorMessage = 'Video file not found';
            });
          }
          return;
        }
        _controller = VideoPlayerController.file(videoFile);
      }

      await _controller!.initialize();

      if (mounted) {
        setState(() {
          _isInitialized = true;
        });
        _controller!.play();
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = 'Video load failed: $e';
        });
      }
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 视频播放器
          if (_errorMessage != null)
            Center(
              child: Text(
                _errorMessage!,
                style: TextStyle(color: Colors.white),
              ),
            )
          else if (_isInitialized && _controller != null)
            GestureDetector(
              onTap: () {
                setState(() {
                  if (_controller!.value.isPlaying) {
                    _controller!.pause();
                  } else {
                    _controller!.play();
                  }
                });
              },
              child: SizedBox.expand(
                child: FittedBox(
                  fit: BoxFit.cover,
                  child: SizedBox(
                    width: _controller!.value.size.width,
                    height: _controller!.value.size.height,
                    child: VideoPlayer(_controller!),
                  ),
                ),
              ),
            )
          else
            Center(child: CircularProgressIndicator(color: ColorPalette.blue1)),
          // 返回按钮
          Positioned(
            top: Platform.isIOS ? 60.h : 40.h,
            left: 16.w,
            child: GestureDetector(
              onTap: () => Navigator.of(context).pop(),
              child: Container(
                width: 40.w,
                height: 40.w,
                decoration: BoxDecoration(
                  color: Colors.white.withValues(alpha: 0.5),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.chevron_left_rounded,
                  color: Colors.white,
                  size: 36.w,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
